<script setup></script>

<template>
  <div>
    <div class="dashboard-layout">
      <div class="carousel-section">
        <div class="carousel-wrapper">
          <el-carousel
            indicator-position="outside"
            :interval="2000"
            height="500px"
            arrow="always"
            trigger="click"
            class="custom-carousel"
          >
            <el-carousel-item
              v-for="(item, index) in images"
              :key="index"
              class="custom-carousel-item"
            >
              <div>
                <img
                  :src="item"
                  alt="carousel image"
                  class="carousel-image"
                  width="100%"
                  height="50%"
                />
              </div>
            </el-carousel-item>
          </el-carousel>
        </div>
      </div>
      <div class="button-section">
        <div @click="goToIdea()">
          <div class="card-dark-yellow">
            <div class="promo-card-overlay">
              <div class="promo-card-container">
                <h2>发个帖子</h2>
                <div>Become an idea creator</div>
              </div>
            </div>
          </div>
        </div>

        <div @click="goToJob()">
          <div class="card-dark-purple">
            <div class="promo-card-overlay">
              <div class="promo-card-container">
                <h2>做点任务</h2>
                <div>Do some tasks</div>
              </div>
            </div>
          </div>
        </div>

        <!-- <div @click="goToChallenge">
          <div class="card-dark-red">
            <div class="promo-card-overlay">
              <div class="promo-card-container">
                <h2>试试挑战</h2>
                <div>Submit theme ideas</div>
              </div>
            </div>
          </div>
        </div> -->

        <!-- ... existing code ... -->
        <div v-if="getRole() === 'admin'" @click="goToPublishJob">
          <div class="card-dark-blue">
            <div class="promo-card-overlay">
              <div class="promo-card-container">
                <h2>发布任务</h2>
                <div>Submit theme ideas</div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
    
    <!-- 添加最新任务展示区域 -->
    <div class="latest-jobs-section">
      <h2 class="section-title">最新任务</h2>
      <div 
        v-loading="jobsLoading"
        element-loading-text="加载中..."
        element-loading-spinner="el-icon-loading"
        element-loading-background="rgba(255, 255, 255, 0.8)"
        class="jobs-container-wrapper"
      >
        <div class="jobs-container">
          <div v-for="job in latestJobs" :key="job.jobId" class="job-card" @click="goToJobDetail(job.jobId)">
            <div class="job-card-image">
              <img :src="getBackgroundImage(job)" :key="job.jobId" alt="任务图片" />
            </div>
            <div class="job-card-content">
              <h3 class="job-title">{{ job.title }}</h3>
              <!-- <p class="job-description">{{ job.description }}</p> -->
              <div class="job-meta">
                <span class="job-date">{{ formatDate(job.createdAt) }}</span>
                <span class="job-status">{{ job.status }}</span>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import a from "/src/assets/images/hover/a.jpg";
import b from "/src/assets/images/hover/b.jpg";
import c from "/src/assets/images/hover/c.jpg";
import { getRole, getUsername } from "@/api/auth";
import { fetchActivities } from "@/api/api";

export default {
  data() {
    return {
      bannerHeight: 200,
      images: [a, b, c],
      buttons: [
        { index: "3", title: "创意", subtitle: "Become an idea creator" },
        {
          index: "2",
          tab: "2",
          title: "活动",
          subtitle: "Share your creativity",
        },
        { index: "2", tab: "3", title: "挑战", subtitle: "Submit theme ideas" },
      ],
      latestJobs: [],
      defaultImage: require('@/assets/images/default-king.png'), // 修改这里

      jobsLoading: false, // 添加加载状态
      imageCache: new Map(), // 用于缓存图片URL
    };
  },
  methods: {
    sendMessage(index, tab) {
      this.$emit("receiveMessage", index, tab);
    },
    setSize() {
      this.bannerHeight = document.body.clientWidth / 4;
    },
    goToIdea() {
      this.$router.push({ name: "upload_activity" });
    },
    goToChallenge() {
      this.$router.push({ name: "Challenge" });
    },
    goToActivity() {
      this.$router.push({ name: "activity" });
    },
    goToJob() {
      this.$router.push({ name: "job" });
    },
    goToPublishTask() {
      this.$router.push({ name: "publish_task" });
    },
    goToPublishJob() {
      getRole();
      this.$router.push({ name: "publish_job" });
    },
    async fetchLatestJobs() {
      this.jobsLoading = true; // 开始加载
      try {
        const jobs = await fetchActivities("/jobs?page=1&size=5");
        this.latestJobs = jobs.records;
      } catch (error) {
        console.error("获取最新任务失败:", error);
        this.$message.error('获取最新任务失败');
      } finally {
        this.jobsLoading = false; // 结束加载
      }
    },
    formatDate(dateString) {
      const date = new Date(dateString);
      return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')}`;
    },
    goToJobDetail(jobId) {
      this.$router.push({ name: 'job_detail', params: { id: jobId } });
    },
    handleImageError(e) {
      e.target.src = this.defaultImage;
    },
    getImageUrl(job) {
      // 如果有图片链接就使用
      if (job.imageSrc && job.imageSrc.trim()) {
        return encodeURI(job.imageSrc.trim());
      }
      // 否则使用本地默认图片
      return require("@/assets/images/default-king.png");
    },
    loadBackgroundImage(job) {
      // 如果已经有缓存，直接返回缓存的URL
      if (this.imageCache.has(job.jobId)) {
        return this.imageCache.get(job.jobId);
      }

      const url = this.getImageUrl(job);
      // 如果是https链接，直接转换为http
      const finalUrl = url.startsWith('https://') ? url.replace('https://', 'http://') : url;
      
      const img = new Image();
      img.onload = () => {
        this.imageCache.set(job.jobId, finalUrl);
        this.$forceUpdate();
      };
      
      img.onerror = () => {
        console.error('Image load failed:', finalUrl);
        const defaultImage = require("@/assets/images/default-king.png");
        this.imageCache.set(job.jobId, defaultImage);
        this.$forceUpdate();
      };
      
      img.src = finalUrl;
      return finalUrl;
    },
    getBackgroundImage(job) {
      // 如果缓存中有，直接返回
      if (this.imageCache.has(job.jobId)) {
        return this.imageCache.get(job.jobId);
      }
      // 否则加载图片
      return this.loadBackgroundImage(job);
    },
  },
  mounted() {
    this.setSize();
    window.addEventListener(
      "resize",
      () => {
        this.setSize();
      },
      false
    );
    this.fetchLatestJobs();
  },
  watch: {
    jobs: {
      handler(newJobs) {
        // 当jobs更新时，预加载所有图片
        if (newJobs) {
          newJobs.forEach(job => {
            this.loadBackgroundImage(job);
          });
        }
      },
      immediate: true
    }
  },
};
</script>

<style scoped>
/* 更新布局相关的样式 */
.dashboard-layout {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  gap: 2vw; /* 使用vw单位使间距随视窗宽度变化 */
  padding: 0 2vw; /* 两侧添加padding，防止紧贴屏幕边缘 */
  max-width: 1600px; /* 限制最大宽度 */
  margin: 0 auto; /* 居中显示 */
  height: 500px;
}

.carousel-section {
  flex: 1;
  min-width: 0; /* 防止flex项溢出 */
  max-width: 75%; /* 限制最大宽度 */
}

.carousel-wrapper {
  height: 100%;
  border-radius: 10px;
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.2);
}

.button-section {
  width: 273px; /* 保持按钮固定宽度 */
  flex-shrink: 0; /* 防止按钮压缩 */
}

/* 添加媒体查询以适应不同屏幕尺寸 */
@media (max-width: 1200px) {
  .dashboard-layout {
    gap: 1.5vw;
  }
  
  .carousel-section {
    max-width: 70%;
  }
}

@media (max-width: 992px) {
  .dashboard-layout {
    flex-direction: column;
    height: auto;
    gap: 20px;
  }
  
  .carousel-section {
    max-width: 100%;
    margin-bottom: 20px;
  }
  
  .button-section {
    width: 100%;
    display: flex;
    flex-wrap: wrap;
    justify-content: center;
    gap: 15px;
  }
}

/* Carousel Item Styles */
.custom-carousel-item h3 {
  color: #475669;
  font-size: 18px;
  opacity: 0.75;
  margin: 0;
}

.custom-carousel-item:nth-child(2n) {
  background-color: #99a9bf;
}

.custom-carousel-item:nth-child(2n + 1) {
  background-color: #d3dce6;
}

.custom-carousel-item {
  border-radius: 10px; /* 圆角 */
}

.carousel-image {
  object-fit: scale-down;
  width: 100%;
  height: 100%;
}

/* 按钮内容样式 */
.card-dark-yellow {
  background-image: url("../assets/images/titles/idea-brick.svg"),
    radial-gradient(100% 671.97% at 0 0, #ffbd00 0, #bf8c00 100%);
  background-size: contain; /* 保持图片原始比例 */
  background-position: 100% center; /* 使图像靠右对齐并居中显示 */
  background-repeat: no-repeat;
  height: 90px;
  width: 273px;
  border-radius: 10px;
}

.card-dark-purple {
  background-image: url("../assets/images/titles/contest-ribbon.svg"),
    radial-gradient(100% 671.97% at 0 0, #6f58ce 0, #443a8d 100%);
  background-size: contain; /* 保持图片原始比例 */
  background-position: 100% center; /* 使图像靠右对齐并居中显示 */
  background-repeat: no-repeat;
  height: 90px;
  width: 273px;
  color: white; /* 设置字体颜色为白色 */
  border-radius: 10px;
}

.card-dark-red {
  background-image: url("../assets/images/titles/activity-lightning.svg"),
    radial-gradient(100% 671.97% at 0 0, #cd264b 0, #8a1232 100%);
  background-size: contain; /* 保持图片原始比例 */
  background-position: 100% center; /* 使图像靠右对齐并居中显示 */
  background-repeat: no-repeat;
  height: 90px;
  width: 273px;
  color: white; /* 设置字体颜色为白色 */
  border-radius: 10px;
}

/* ... existing styles ... */

.card-dark-blue {
  background-image: url("../assets/images/titles/shop-book.svg"),
    radial-gradient(100% 671.97% at 0 0, #0073b7 0, #005387 100%);
  background-size: contain;
  background-position: 100% center;
  background-repeat: no-repeat;
  height: 90px;
  width: 273px;
  color: white;
  border-radius: 10px;
}

/* 更新动画选择器，包含新的卡片类 */
.card-dark-yellow,
.card-dark-purple,
.card-dark-red,
.card-dark-blue {
  animation: float 3s ease-in-out infinite;
}

.promo-card-overlay {
  display: block;
  position: relative;
  text-align: left;
}

/* Promo Card Container Styles */
.promo-card-container {
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: flex-start; /* 左对齐 */
  height: 100%;
  width: 100%;
  margin-left: 35px;
  margin-top: 15px;
}

.promo-card-container h2 {
  display: block;
  font-size: 1.5em;
  margin-block-start: 0.83em;
  margin-block-end: 0.83em;
  margin-inline-start: 0;
  margin-inline-end: 0;
  margin-top: 15px;
  unicode-bidi: isolate;
  font-family: "Cera-Bold", sans-serif;
  font-weight: 700;
  line-height: 2.1rem;
  text-transform: uppercase;
  text-align: left; /* 确保文本左对齐 */
}

.promo-card-container div {
  font-size: 14px;
  font-style: italic;
  text-align: left; /* 确保文本左对齐 */
  font-family: "Cera-Bold", sans-serif;
  margin-top: -15px;
  margin-bottom: 15px;
}

/* ... existing styles ... */

/* 添加按钮通用悬浮效果 */
.button-section > div {
  transition: all 0.3s ease;
  cursor: pointer;
}

.button-section > div:hover {
  transform: translateY(-5px) scale(1.02);
  box-shadow: 0 10px 20px rgba(0, 0, 0, 0.2);
}

/* 添加浮动动画 */
.card-dark-yellow,
.card-dark-purple,
.card-dark-red {
  animation: float 3s ease-in-out infinite;
}

/* 错开浮动动画时间 */
.button-section > div:nth-child(2) > div {
  animation-delay: 0.5s;
}

.button-section > div:nth-child(3) > div {
  animation-delay: 1s;
}

.button-section > div:nth-child(4) > div {
  animation-delay: 1.5s;
}

@keyframes float {
  0% {
    transform: translateY(0px);
  }
  50% {
    transform: translateY(-10px);
  }
  100% {
    transform: translateY(0px);
  }
}

/* 最新任务区域样式 */
.latest-jobs-section {
  margin-top: 40px;
  padding: 0 2vw;
  max-width: 1600px;
  margin-left: auto;
  margin-right: auto;
}

.section-title {
  font-size: 24px;
  font-weight: bold;
  margin-bottom: 20px;
  color: #333;
}

.jobs-container {
  display: flex;
  justify-content: flex-start;  /* 改为flex-start以减少间距 */
  gap: 12px;  /* 减小卡片之间的间距 */
  padding: 10px 0;
  overflow: hidden;
}

.job-card {
  flex: 1;
  max-width: calc(20% - 16px);
  min-width: 0;
  background: white;
  border-radius: 10px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
  transition: transform 0.3s ease, box-shadow 0.3s ease;
  cursor: pointer;
  overflow: hidden;
}

.job-card-image {
  width: 100%;
  height: 160px;
  overflow: hidden;
}

.job-card-image img {
  width: 100%;
  height: 100%;
  object-fit: cover;
  transition: transform 0.3s ease;
}

.job-card-content {
  padding: 15px;
}

.job-title {
  font-size: 16px;
  font-weight: bold;
  margin-bottom: 8px;
  color: #333;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.job-description {
  font-size: 13px;
  color: #666;
  margin-bottom: 12px;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
  overflow: hidden;
  height: 36px;
}

.job-meta {
  display: flex;
  justify-content: space-between;
  align-items: center;
  font-size: 12px;
  color: #999;
}

.job-date {
  background: #f5f5f5;
  padding: 4px 8px;
  border-radius: 4px;
}

.job-status {
  color: #0073b7;
  font-weight: 500;
}

.job-card:hover {
  transform: translateY(-5px);
  box-shadow: 0 5px 15px rgba(0, 0, 0, 0.2);
}

.job-card:hover .job-card-image img {
  transform: scale(1.05);
}

@media (max-width: 1200px) {
  .job-card {
    max-width: calc(20% - 12px);
  }
  
  .jobs-container {
    gap: 15px;
  }
}

@media (max-width: 992px) {
  .jobs-container {
    flex-wrap: wrap;
    justify-content: center;
  }
  
  .job-card {
    max-width: calc(33.33% - 20px);
    margin-bottom: 20px;
  }
}

@media (max-width: 768px) {
  .job-card {
    max-width: calc(50% - 15px);
  }
}

@media (max-width: 480px) {
  .job-card {
    max-width: 100%;
  }
}

/* 添加加载动画容器样式 */
.jobs-container-wrapper {
  min-height: 300px; /* 确保加载时有足够的高度显示动画 */
  position: relative;
}

/* 自定义加载动画样式 */
:deep(.el-loading-spinner) {
  .el-loading-text {
    color: #409EFF;
    font-size: 16px;
    margin-top: 10px;
  }
  
  .circular {
    width: 42px;
    height: 42px;
  }
}

/* 调整加载背景样式 */
:deep(.el-loading-mask) {
  border-radius: 10px;
}
</style>

